<template>
  <div class="order-list">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="订单号">
          <el-input v-model="searchForm.orderNo" placeholder="请输入订单号" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" style="width: 150px" placeholder="请选择状态" clearable>
            <el-option label="待确认" :value="0" />
            <el-option label="已确认" :value="1" />
            <el-option label="已取消" :value="2" />
            <el-option label="已完成" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 订单列表 -->
    <el-table
      v-loading="loading"
      :data="orderList"
      border
      style="width: 100%"
    >
      <el-table-column prop="orderNo" label="订单号" width="200" />
      <el-table-column prop="restaurantName" label="餐厅" />
      <el-table-column prop="tableNumber" label="餐桌号" width="100" />
      <el-table-column prop="contactName" label="联系人" width="100" />
      <el-table-column prop="contactPhone" label="联系电话" width="120" />
      <el-table-column prop="personCount" label="用餐人数" width="100" />
      <el-table-column prop="totalAmount" label="总金额" width="100">
        <template #default="{ row }">
          ¥{{ row.totalAmount }}
        </template>
      </el-table-column>
      <el-table-column prop="reservationTime" label="预订时间" width="180" />
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getOrderStatusType(row.status)">
            {{ getOrderStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button
            v-if="row.status === 0"
            type="success"
            link
            @click="handleConfirm(row)"
          >
            确认
          </el-button>
          <el-button
            v-if="row.status === 0 || row.status === 1"
            type="danger"
            link
            @click="handleCancel(row)"
          >
            取消
          </el-button>
          <el-button
            v-if="row.status === 1"
            type="primary"
            link
            @click="handleComplete(row)"
          >
            完成
          </el-button>
          <el-button type="primary" link @click="handleDetail(row)">
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog
      title="订单详情"
      v-model="detailVisible"
      width="600px"
    >
      <div v-if="currentOrder" class="order-detail">
        <div class="basic-info">
          <h3>基本信息</h3>
          <p><span class="label">订单号：</span>{{ currentOrder.orderNo }}</p>
          <p><span class="label">餐厅：</span>{{ currentOrder.restaurantName }}</p>
          <p><span class="label">餐桌号：</span>{{ currentOrder.tableNumber }}</p>
          <p><span class="label">预订时间：</span>{{ currentOrder.reservationTime }}</p>
          <p><span class="label">用餐人数：</span>{{ currentOrder.personCount }}人</p>
          <p><span class="label">联系人：</span>{{ currentOrder.contactName }}</p>
          <p><span class="label">联系电话：</span>{{ currentOrder.contactPhone }}</p>
          <p><span class="label">备注：</span>{{ currentOrder.remark || '无' }}</p>
        </div>
        <div class="dishes-info">
          <h3>菜品信息</h3>
          <el-table :data="currentOrder.orderDetails" border>
            <el-table-column prop="dishName" label="菜品名称" />
            <el-table-column prop="price" label="单价">
              <template #default="{ row }">
                ¥{{ row.price }}
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="100" />
            <el-table-column prop="subtotal" label="小计">
              <template #default="{ row }">
                ¥{{ row.subtotal }}
              </template>
            </el-table-column>
          </el-table>
          <div class="total">
            总计：<span class="price">¥{{ currentOrder.totalAmount }}</span>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { getOrderList, getOrderDetail, confirmOrder, completeOrder, cancelOrder } from '@/api/order'
import dayjs from 'dayjs'

const loading = ref(false)
const orderList = ref([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)
const detailVisible = ref(false)
const currentOrder = ref(null)

const searchForm = ref({
  orderNo: '',
  status: null
})

// 获取订单列表
const fetchOrderList = async () => {
  try {
    loading.value = true
    const res = await getOrderList({
      page: page.value,
      pageSize: pageSize.value,
      ...searchForm.value
    })
    orderList.value = res.data.records
    total.value = res.data.total
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  page.value = 1
  fetchOrderList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    orderNo: '',
    status: null
  }
  handleSearch()
}

// 处理确认订单
const handleConfirm = async (row) => {
  try {
    await ElMessageBox.confirm('确定要确认该订单吗？')
    await confirmOrder(row.id)
    ElMessage.success('确认成功')
    fetchOrderList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认失败:', error)
      ElMessage.error('确认失败')
    }
  }
}

// 处理完成订单
const handleComplete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要完成该订单吗？')
    await completeOrder(row.id)
    ElMessage.success('操作成功')
    fetchOrderList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

// 处理取消订单
const handleCancel = async (row) => {
  try {
    await ElMessageBox.confirm('确定要取消该订单吗？')
    await cancelOrder(row.id)
    ElMessage.success('取消成功')
    fetchOrderList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消失败:', error)
      ElMessage.error('取消失败')
    }
  }
}

// 处理查看详情
const handleDetail = async (row) => {
  try {
    const res = await getOrderDetail(row.id)
    currentOrder.value = res.data
    detailVisible.value = true
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
  }
}

// 获取订单状态类型
const getOrderStatusType = (status) => {
  const types = {
    0: 'warning',
    1: 'primary',
    2: 'danger',
    3: 'success'
  }
  return types[status] || 'info'
}

// 获取订单状态文本
const getOrderStatusText = (status) => {
  const texts = {
    0: '待确认',
    1: '已确认',
    2: '已取消',
    3: '已完成'
  }
  return texts[status] || '未知状态'
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchOrderList()
}

const handleCurrentChange = (val) => {
  page.value = val
  fetchOrderList()
}

onMounted(() => {
  fetchOrderList()
})
</script>

<style scoped lang="scss">
.order-list {
  padding: 20px;

  .search-bar {
    margin-bottom: 20px;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

.order-detail {
  .basic-info,
  .dishes-info {
    margin-bottom: 20px;

    h3 {
      margin: 0 0 15px;
      padding-bottom: 10px;
      border-bottom: 1px solid #eee;
    }
  }

  .basic-info {
    p {
      margin: 8px 0;

      .label {
        display: inline-block;
        width: 100px;
        color: #666;
      }
    }
  }

  .dishes-info {
    .total {
      margin-top: 15px;
      text-align: right;
      font-size: 16px;

      .price {
        color: #f56c6c;
        font-size: 20px;
        font-weight: bold;
      }
    }
  }
}
</style>
